package vcp.client.GUI.mvc.model;

import java.io.IOException;

import vcp.client.exceptions.EmptyRequestException;
import vcp.client.interfaces.IObservable;
import vcp.client.interfaces.IObserver;
import vcp.client.interfaces.delegates.IControllerModelDelegate;
import vcp.client.request.Request;
import vcp.client.utility.Common.UserNotification;
import vcp.enums.PopUpMessageType;

/**
 * 
 * @author VCP team
 *         <p>
 *         Abstract class for models
 *         </p>
 */
public abstract class UIAbstractModel implements IObserver
{
	protected IObservable model;
	/**
	 * controller delegate
	 */
	protected IControllerModelDelegate controllerDelegate;

	public void setControllerDelegate ( IControllerModelDelegate controllerDelegate )
	{
		this.controllerDelegate = controllerDelegate;
	}

	/**
	 * 
	 * @param model
	 */
	protected UIAbstractModel ( IObservable model )
	{
		this.model = model;
	}

	/**
	 * clear the model before bring new data
	 */
	public void clearModel ()
	{

	}

	/**
	 * register it for getting updates
	 */
	public void shouldRegisterForUpdates ()
	{

	}

	/**
	 * send the request
	 * 
	 * @param request
	 *            by its type
	 * @param withLoading
	 *            boolean that save the loading status
	 */
	final protected void sendRequest ( Request request, boolean withLoading )
	{
		boolean success = true;
		try
		{
			if ( withLoading )
			{
				this.controllerDelegate.loadingStart();
			}
			this.model.registerAndSendRequest(request, this);
		}
		catch ( EmptyRequestException e )
		{
			this.controllerDelegate.showPopUpMessage(e.getMessage(), PopUpMessageType.ERROR);
			success = false;
		}
		catch ( IOException e )
		{
			this.controllerDelegate.showPopUpMessage(UserNotification.FAIL_TO_SEND_TO_SERVER, PopUpMessageType.ERROR);
			success = false;
		}

		if ( ! success )
		{
			this.controllerDelegate.loadingStop();
		}
	}

	/****************************************************************************************************************************
	 *** Observer methods ***
	 ****************************************************************************************************************************/
	@Override
	public void update ( Object data )
	{
	}

	@Override
	public void updateWithReferesh ( Object data )
	{
	}
}
